import { Module } from '@nestjs/common'
import { APP_GUARD } from '@nestjs/core'
import { ConfigModule } from '@nestjs/config'
import { TypeOrmModule } from '@nestjs/typeorm'
import { getTypeOrmConfig } from './shared/utils/typeorm.config'
import { JwtAuthGuard } from 'src/modules/auth/guards/jwt-auth.guard'
import { PermissionsGuard } from 'src/modules/rbac/guards/permissions.guard'
import config from './config'
import { MetadataModule } from './modules/metadata/metadata.module'
import { CrudModule } from './modules/crud/crud.module'
import { AuthModule } from './modules/auth/auth.module'
import { UserModule } from './modules/user/user.module'
import { RbacModule } from './modules/rbac/rbac.module'
import { FileModule } from './modules/file/file.module'
import { PluginModule } from './modules/plugin/plugin.module'
import { ConfigModule as SystemConfigModule } from './modules/config/config.module'
import { MulterModule } from '@nestjs/platform-express'
import { CacheModule } from '@nestjs/cache-manager'

@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true }),
    CacheModule.register({ isGlobal: true }),
    TypeOrmModule.forRoot(getTypeOrmConfig()),
    MulterModule.register({
      dest: './uploads',
      limits: { fileSize: config.fileUpload.maxSize },
      fileFilter: (req, file, cb) => {
        const ext = file.originalname.split('.').pop()?.toLowerCase() || ''
        if (!config.fileUpload.allowedExtensions.includes('.' + ext)) {
          return cb(new Error(`只允许上传${config.fileUpload.allowedExtensions.join(', ')}格式的文件`), false)
        }
        cb(null, true)
      },
    }),
    MetadataModule,
    CrudModule,
    AuthModule,
    UserModule,
    RbacModule,
    FileModule,
    PluginModule,
    SystemConfigModule,
  ],
  providers: [
    {
      provide: APP_GUARD,
      useClass: JwtAuthGuard,
    },
    {
      provide: APP_GUARD,
      useClass: PermissionsGuard,
    },
  ],
})
export class AppModule {}
